import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import { Modal, Form, message, Upload, Button, Icon, Row, Col } from 'antd';
import { fetchData } from '../../../components/AjaxConsumer'
import WorkAreaForm from './UpdateForm'
//import reqwest from 'reqwest';

const confirm = Modal.confirm;

export default class UpdateWorkareaPageUp extends Component {
    constructor(props) {
        super(props);
        this.state = {

            fileList: [],
            uploading: false,
        };
    }

    //显示弹框
    showModal = () => {
        this.setState({
            visible: true,
        });
    }
    // 隐藏弹出框
    hideModal = () => {
        this.setState({
            visible: false,
        });
    }
    // 新增工作区
    add = () => {

        this.showModal();//显示弹框
    }
    // 新增/修改后的回调
    handleOk = () => {
        this.hideModal();
        this.refreshHandle();
    }

    handleCancel = () => {
        //表单重置
        this.setState({
           fileList: [],
        });
        // this.refs.modalFrom.resetFields();
        this.hideModal();
    }

    //刷新List列表
    refreshHandle = () => {
        console.log("刷新List列表")
        this.props.refreshHandle();
    }
    handleUpload = () => {
        const { fileList } = this.state;
        const formData = new FormData();
        this.setState({
            uploading: true,
        });
        fileList.forEach((file) => {
            formData.append("file", file);
        });
        //formData.append("name",name);
        $.ajax({
            url: '/wmsrest/material/odsRawUnitnit/file',
            type: 'POST',
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            beforeSend: function () {
                console.log("正在进行，请稍候");
            },

            success: (resData) => {
                let code = resData.code;
                if (code == "1") {
                    Modal.success({
                        title: '提示',
                        content: '上传成功',
                    });
                    this.setState({
                        fileList: [],
                        uploading: false,
                        visible: false,
                    });
                }
                if (code == "-1") {
                    Modal.warning({
                        title: '提示',
                        content: '尚未登录或登录超时，将返回登录页',
                        onOk() {
                            window.location.href = '/';
                        },
                    });
                } else if (code != "1") {
                    Modal.warning({
                        title: '提示',
                        content: resData.msg,
                    });
                    if (typeof (errorCallback) != 'undefined' && errorCallback != null) {
                        errorCallback(resData);
                    }
                } else {
                    if (typeof (callback) != 'undefined' && callback != null) {
                        callback(resData);
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // let code = resData.code;
                // if (code != "1") {
                //     Modal.error({
                //         title: '错误提示',
                //         content: resData.msg,
                //     });
                // }
                
                console.log("ajax请求失败，状态码：", XMLHttpRequest.status, ",状态:", XMLHttpRequest.readyState, ",错误信息:", textStatus);
                let errorMSG = '请求失败！请检查您的网络！';
                if (XMLHttpRequest.status == "404") {
                    errorMSG = '请求地址未找到。';
                    Modal.error({
                        title: '错误提示',
                        content: errorMSG,
                    });
                } else if (XMLHttpRequest.status == "408") {
                    errorMSG = '请求超时!';
                    Modal.warning({
                        title: '错误提示',
                        content: errorMSG,
                    });
                } else if (XMLHttpRequest.status == "500") {
                    errorMSG = '内部服务器错误。';
                    Modal.error({
                        title: '错误提示',
                        content: errorMSG,
                    });
                } else if (textStatus === "timeout") {
                    errorMSG = '请求超时！';
                    Modal.warning({
                        title: '错误提示',
                        content: errorMSG,
                    });
                } else {
                    Modal.error({
                        title: '错误提示',
                        content: errorMSG,
                    });
                }

            }

        });
        // // You can use any AJAX library you like
        // $.ajax({
        //     url: '/wmsrest/material/odsRawUnitnit/file',
        //     method: 'post',
        //     processData: false,
        //     data: formData,
        //     success: () => {
        //         this.setState({
        //             fileList: [],
        //             uploading: false,
        //         });
        //         message.success('upload successfully.');
        //     },
        //     error: () => {
        //         this.setState({
        //             uploading: false,
        //         });
        //         message.error('upload failed.');
        //     },
        // });
        console.log("chnegg")
    }

    download = () => {
//        window.location.href = 'http://localhost:80//template/1.rar';
        this.refs.ifile.src = 'http://10.138.111.96:8088/template/rawUnit.xlsx';
    }

    handleChange = (info) => {
        console.log("45646")
        let fileList = info.fileList;

        // 1. Limit the number of uploaded files
        //    Only to show two recent uploaded files, and old ones will be replaced by the new
        fileList = fileList.slice(-2);

        // 2. read from response and show file link
        fileList = fileList.map((file) => {
            if (file.response) {
                // Component will show file.url as link
                file.url = file.response.url;
            }
            return file;
        });
    }
    render() {
        const { uploading } = this.state;
        const props = {
            action: '/wmsrest/material/odsRawUnitnit/file',
            onRemove: (file) => {
                this.setState(({ fileList }) => {
                    const index = fileList.indexOf(file);
                    const newFileList = fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file) => {
                const isJPG = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                // if (!isJPG) {
                //     message.error('只能上传excel文件!');

                //     return false;
                // }else{
                this.setState(({ fileList }) => ({
                    fileList: [...fileList, file],
                }));
                return false;
                // }
            },
            fileList: this.state.fileList,
            onChange: this.handleChange,
        };


        return (
            <Modal
                style={{ top: '20px' }}
                visible={this.state.visible}
                title={this.state.formTitle ? this.state.formTitle : '批量上传单位换算关系'}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width={this.formAlerSize == 'large' ? '850px' : '400px'}
                footer=''
            >
                <div>
                    <Upload {...props} disabled={this.state.fileList.length >= 1}>
                        <Button>
                            <Icon type="upload" /> 选择文件
                        </Button>
                    </Upload>

                    <Row>
                        <Col span={24} style={{ textAlign: 'center',marginTop:'5px' }}>
                            <Button className="upload-demo-start" type="primary" onClick={this.handleUpload}
                                    disabled={this.state.fileList.length === 0}>
                                上传
                            </Button>
                            <Button className="upload-demo-start" type="primary" style={{ marginLeft: 100 }}
                                    onClick={this.download}>
                                下载模板
                            </Button>
                        </Col>
                    </Row>
                    <iframe ref="ifile" height="0"></iframe>
                </div>
            </Modal>
        )
    }
}